package com.ts.file.controller;

import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import com.ts.common.core.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@RestController
@RequestMapping("/file")
public class FileUplaodController {

    @Value("${ts.ak}")
    private String ak;

    @Value("${ts.sk}")
    private String sk;

    @Value("${ts.bucket}")
    private String bucket;

    @Value("${ts.host}")
    private String host;

    @Autowired
    private UploadManager uploadManager;

    @PostMapping("/upload")
    public Result upload(MultipartFile file) {

        String originalFilename = file.getOriginalFilename();

        String key = "weixin/" + originalFilename;

        // 通过AK和SK这个一个Token
        Auth auth = Auth.create(ak, sk);
        String upToken = auth.uploadToken(bucket);
        try {
            // 上传文件
            Response response = uploadManager.put(file.getBytes(), key, upToken);
            //解析上传成功的结果
            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
            System.out.println(putRet.key);
            System.out.println(putRet.hash);
        } catch (QiniuException ex) {
            Response r = ex.response;
            System.err.println(r.toString());
            try {
                System.err.println(r.bodyString());
            } catch (QiniuException ex2) {
                //ignore
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        return new Result().viewOk(host+key);
    }
}
